/*
 * PACKAGE NAME: com.jodinfo.outmirror.api.reportinventoryanalyze.service
 * FILE    NAME: ReportInventoryAnalyzeDaoImpl.java
 * COPYRIGHT: Copyright(c) © 2016 heroj Company Ltd. All Rights Reserved
 */ 
package com.jodinfo.outmirror.api.reportinventoryanalyze.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.hero.common.web.excel.util.ExcelExport;
import com.hero.core.constant.SysConstant;
import com.hero.core.entity.PageResult;
import com.hero.core.entity.ResponseEntity;
import com.hero.core.exception.AbstractGenericException;
import com.hero.core.exception.BusinessException;
import com.hero.core.util.DateUtils;
import com.hero.core.util.StringUtils;
import com.hero.core.util.ValidationUtil;
import com.jodinfo.outmirror.api.ReportConstant;
import com.jodinfo.outmirror.api.Dymcform.service.DymcformQueryService;
import com.jodinfo.outmirror.api.loseform.entity.LoseformEntity;
import com.jodinfo.outmirror.api.loseform.service.LoseformQueryService;
import com.jodinfo.outmirror.api.loseformbarcode.entity.LoseformBarcodeEntity;
import com.jodinfo.outmirror.api.loseformbarcode.service.LoseformBarcodeQueryService;
import com.jodinfo.outmirror.api.org.entity.OrgEntity;
import com.jodinfo.outmirror.api.org.service.OrgQueryService;
import com.jodinfo.outmirror.api.reportinventoryanalyze.entity.ReportInventoryAnalyzeEntity;
import com.jodinfo.outmirror.api.workflow.entity.UserTask;
import com.jodinfo.outmirror.api.workflow.service.ActivitiTaskQueryService;
import com.taobao.ad.easyschedule.dataobject.JobData;
import com.taobao.ad.easyschedule.dataobject.JobResult;

@Service(value="reportInventoryAnalyzeBizService")
public class ReportInventoryAnalyzeBizServiceImpl implements ReportInventoryAnalyzeBizService{
    private static final Logger logger = LoggerFactory.getLogger(ReportInventoryAnalyzeBizServiceImpl.class);
 	
 	@Resource(name="reportInventoryAnalyzeDmlService")
	private ReportInventoryAnalyzeDmlService ReportInventoryAnalyzeDmlService;
	@Resource(name="reportInventoryAnalyzeQueryService")
	private ReportInventoryAnalyzeQueryService ReportInventoryAnalyzeQueryService;
	@Resource(name="activitiTaskQueryService")
	private ActivitiTaskQueryService activitiTaskQueryService;
	@Resource(name="dymcformQueryService")
	private DymcformQueryService dymcformQueryService;
	@Resource(name="orgQueryService")
	private OrgQueryService orgQueryService;
	@Resource(name="loseformBarcodeQueryService")
	private LoseformBarcodeQueryService loseformBarcodeQueryService;
	@Resource(name="loseformQueryService")
	private LoseformQueryService loseformQueryService; 
	
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeBizService#addReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity
	 * @return int
	 */
	public ResponseEntity addReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity) {
			ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
			  	 int i =  ReportInventoryAnalyzeDmlService.addReportInventoryAnalyze(ReportInventoryAnalyzeEntity);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeBizService#updateReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity
	 * @return ResponseEntity
	 */
	public ResponseEntity updateReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				int i = ReportInventoryAnalyzeDmlService.updateReportInventoryAnalyze(ReportInventoryAnalyzeEntity);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeBizService#queryAllReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity
	 * @return String
	 */
	public String queryAllReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity) {
		return JSON.toJSONString(ReportInventoryAnalyzeQueryService.queryAllReportInventoryAnalyze(ReportInventoryAnalyzeEntity));
	} 
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeBizService#queryAllReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity
	 * @return PageResult
	 */
	public String queryListForPageReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity) {
		return new PageResult( ReportInventoryAnalyzeQueryService.queryListForPageReportInventoryAnalyze(ReportInventoryAnalyzeEntity), ReportInventoryAnalyzeQueryService.queryCountReportInventoryAnalyze(ReportInventoryAnalyzeEntity)).toString();
	} 
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeQueryService#queryById(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param BigInteger id
	 * @return
	 */
	public ReportInventoryAnalyzeEntity queryById(BigInteger id) {
		return ReportInventoryAnalyzeQueryService.queryById(id);
	}
	
	public void exportReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity, HttpServletResponse response) {
		List<ReportInventoryAnalyzeEntity> exportList = null;
		String ids = ReportInventoryAnalyzeEntity.getIds();
		if (ValidationUtil.isNullOrEmptyString(ids)) {
			exportList =ReportInventoryAnalyzeQueryService.queryAllReportInventoryAnalyze(ReportInventoryAnalyzeEntity);
		} else {
			String[] idArray = ids.split(",");
			List<BigInteger> idList = new ArrayList<BigInteger>();
			for(String id : idArray) {
				idList.add(new BigInteger(id));
			}
			exportList = ReportInventoryAnalyzeQueryService.queryByIds(idList);
			// 将字典中的code转换为name
		   //convertCodeToName(exportList);
		}
		ExcelExport.exportExcel(exportList, "ReportInventoryAnalyzeEntityExcel", "ReportInventoryAnalyzeEntity信息", response);
	}
	
	/** 
	 * 批量删除 数据处理
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeQueryService#queryById(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param BigInteger id
	 * @return
	 */
	public ResponseEntity batchDelReportInventoryAnalyze(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity) {
		String ids = ReportInventoryAnalyzeEntity.getIds();
		String[] idArray = ids.split(",");
		List<ReportInventoryAnalyzeEntity> ReportInventoryAnalyzeEntityList = new ArrayList<ReportInventoryAnalyzeEntity>();
		for(String id : idArray) {
			ReportInventoryAnalyzeEntity ReportInventoryAnalyzeModel = new ReportInventoryAnalyzeEntity();
			ReportInventoryAnalyzeModel.setId(new BigInteger(id));
//			ReportInventoryAnalyzeModel.setLastUpdateUsrName(UserContext.getUser().getName());
//			ReportInventoryAnalyzeModel.setLastUpdateTime(DateUtils.getCurrentTime());
//			ReportInventoryAnalyzeModel.setIsDel(SysConstant.IS_DEL_Y);
			ReportInventoryAnalyzeModel.setUpdateTime(DateUtils.getCurrentTime());
			ReportInventoryAnalyzeEntityList.add(ReportInventoryAnalyzeModel);
		}
		return batchUpdateReportInventoryAnalyze(ReportInventoryAnalyzeEntityList);
	}
	
	/**
	 * 执行批量删除操作
	 * @author weiwei
	 * @date 2017年3月13日 上午11:40:31
	 * @param ReportInventoryAnalyzeList
	 * @return
	 */
	public ResponseEntity batchUpdateReportInventoryAnalyze(List<ReportInventoryAnalyzeEntity> ReportInventoryAnalyzeList) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				int i = ReportInventoryAnalyzeDmlService.batchUpdateReportInventoryAnalyze(ReportInventoryAnalyzeList);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	
	/**
	 * 
	 * @author weiwei
	 * @date 2017年3月13日 上午10:24:53
	 * @see  com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeQueryService#queryById(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param map
	 * @param excelimportcontext
	 * @param s
	 * @return
	 * @throws Exception
	 */
	/*public List<BigInteger> insertData(Map<Integer, List<Object>> map,ExcelImportContext excelimportcontext, String s) throws Exception {
		String usrName = UserContext.getUser().getName();//数据创建人
		String creatTime = DateUtils.getCurrentTime();
		List<ReportInventoryAnalyzeEntity> ReportInventoryAnalyzeList = validateReportInventoryAnalyzeData(map, excelimportcontext,usrName,creatTime);
		if (!excelimportcontext.hasError() && ReportInventoryAnalyzeList.size() > 0) {
			batchAddReportInventoryAnalyze(ReportInventoryAnalyzeList);
		}
		return null;
	}*/
	
	/**
	 * 
	 * TODO 验证数据 处理业务数据
	 * @author weiwei
	 * @date 2017年3月13日 上午9:33:30
	 * @see  com.jodinfo.outmirror.implementation.reportinventoryanalyze.ReportInventoryAnalyzeQueryService#queryById(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeEntity)
	 * @param ReportInventoryAnalyzeList
	 * @return
	 */
	/*public List<ReportInventoryAnalyzeEntity> validateReportInventoryAnalyzeData(Map<Integer, List<Object>> map,ExcelImportContext excelimportcontext,String usrName,String creatTime) {
		ExcelImportContext.DataError errorMsg = null;
		List<ReportInventoryAnalyzeEntity> ReportInventoryAnalyzeList = new ArrayList<ReportInventoryAnalyzeEntity>();
		for (Map.Entry<Integer, List<Object>> entity : map.entrySet()) {
			List<Object> excelModelList = entity.getValue();
			if (ValidationUtil.isNullOrEmptyCollection(excelModelList)) {
		//		errorMsg = excelimportcontext.new DataError(InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET,
		//				"导入数据为空！",InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET);
		//		excelimportcontext.push(errorMsg);
			}else{
				//TODO 验证对应数据
				for (int i =0;i<excelModelList.size();i++) {
					ReportInventoryAnalyzeEntity ReportInventoryAnalyzeModel = (ReportInventoryAnalyzeEntity) excelModelList.get(i);
	 				if (checkDataByEntityModel(shShopModel, excelimportcontext, i)) {
						break;
					}
					//TODO 实体对象加入对应参数值 
					ReportInventoryAnalyzeModel = setEntityData(ReportInventoryAnalyzeModel,usrName, creatTime);
					ReportInventoryAnalyzeList.add(ReportInventoryAnalyzeModel);
				}
			}
		}
		return ReportInventoryAnalyzeList;
	}*/
	
	/**
	 * 
	 * 单个导入实体数据校验 有错误返回true
	 * @author weiwei
	 * @date 2017年3月28日 下午3:59:17
	 * @param eqEquipmentModel
	 * @param excelimportcontext
	 * @param i
	 * @return
	 */
	/*public boolean checkDataByEntityModel(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeModel,ExcelImportContext excelimportcontext,int i) {
		if (checkSingleData(excelimportcontext, ReportInventoryAnalyzeModel.getIsDel, i+2,"错误信息") 
			//	|| checkSingleData(excelimportcontext, ReportInventoryAnalyzeModel.getEquipmentColor(), i+2, "颜色为空！")
			//	||checkSingleData(excelimportcontext, ReportInventoryAnalyzeModel.getEquipmentModel(), i+2, "型号为空！")
				) {
			return true;
		}else{
			return false;
		}
	}*/
	
	/**
	 * 
	 * 设置报错信息
	 * @author weiwei
	 * @date 2017年3月22日 下午5:17:37
	 * @param excelimportcontext
	 * @param rowNumId
	 * @param errorMessage
	 * @param sheetNumId 现在只有一个sheet 就不传值 默认值即可
	 */
	/*public boolean checkSingleData(ExcelImportContext excelimportcontext,String checkVal,int rowNumId,String errorMessage) {
		boolean flag = false;
		ExcelImportContext.DataError errorMsg = null;
		if (ValidationUtil.isNullOrEmptyString(checkVal)) {
			errorMsg = excelimportcontext.new DataError(rowNumId,errorMessage,InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET);
			excelimportcontext.push(errorMsg);
			flag = true;
		}
		return flag;
	}*/
	
	/**
	 * 
	 * 导入单个实体添加统一导入人及导入时间
	 * @author zhuxiaoliu
	 * @date 2017年3月28日 下午4:05:15
	 * @param eqEquipmentModel
	 * @param usrName
	 * @param creatTime
	 * @return
	 */
	/*public ReportInventoryAnalyzeEntity setEntityData(ReportInventoryAnalyzeEntity ReportInventoryAnalyzeModel,String usrName,String creatTime) {
		
		//ReportInventoryAnalyzeModel.setEquipmentId(InventoryConstantUtil.EQ_EQUIPMENT_SEQUENCE);
		ReportInventoryAnalyzeModel.setCreateTime(creatTime);
		ReportInventoryAnalyzeModel.setCreateUsrName(usrName);
		ReportInventoryAnalyzeModel.setLastUpdateUsrName(usrName);
		ReportInventoryAnalyzeModel.setLastUpdateTime(creatTime);
		ReportInventoryAnalyzeModel.setIsDel(SysConstant.IS_DEL_N);
		return ReportInventoryAnalyzeModel;
	}*/
	
	
	/**
	 * 
	 * 执行批插入操作
	 * @author weiwei
	 * @date 2017年3月13日 上午11:37:14
	 * @param {moduleName}List
	 * @return
	 */
	public ResponseEntity batchAddReportInventoryAnalyze(List<ReportInventoryAnalyzeEntity> ReportInventoryAnalyzeList) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
		try{
			int i = ReportInventoryAnalyzeDmlService.batchAddReportInventoryAnalyze(ReportInventoryAnalyzeList);
			 rs.setMessage(i+"条记录插入操作成功");
		 }catch(AbstractGenericException e){
			logger.error(e.getFullMessage());
			rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
		}catch(Exception e){
			String errorMessage = StringUtils.toString(e);
			logger.error(errorMessage);
			rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
		}
		return rs;
	}
	/**
	 * 
	 * 
	 * @author cao.weiwei
	 * @date 2017年6月28日 下午4:13:33
	 * @see com.jodinfo.outmirror.api.reportinventoryanalyze.service.ReportInventoryAnalyzeBizService#queryAnalyzeData(com.jodinfo.outmirror.api.reportinventoryanalyze.entity.ReportInventoryAnalyzeEntity)
	 * @param reportInventoryAnalyzeEntity
	 * @return
	 */
	public ResponseEntity queryAnalyzeData(
			ReportInventoryAnalyzeEntity reportInventoryAnalyzeEntity) {
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		Map<String,Object> result = new HashMap<String,Object>();
		
		List<ReportInventoryAnalyzeEntity> list = ReportInventoryAnalyzeQueryService.queryByGroup(reportInventoryAnalyzeEntity);
		setSumData(list, result, reportInventoryAnalyzeEntity);
		rs.setResult(result);
		return rs;
	}
	/**
	 * 查询店铺数量信息,设备数量信息,日期信息,
	 * @author cao.weiwei
	 * @date 2017年6月28日 下午4:52:46
	 * @param sumObject
	 * @param list
	 * @param calcType
	 */
	private void setSumData(List<ReportInventoryAnalyzeEntity> list,
			Map<String, Object> result,
			ReportInventoryAnalyzeEntity reportInventoryAnalyzeEntity) {
		List<String> shop_sum = new ArrayList<String>();
		List<String> eq_sum = new ArrayList<String>();
		List<String> timeitem = new ArrayList<String>();

		// 如果没有截止时间,补充截止时间
		if(StringUtils.isEmpty(reportInventoryAnalyzeEntity.getDateEnd())){
			reportInventoryAnalyzeEntity.setDateEnd(DateUtils.getCurrentTime().substring(0, 10));
		}
		// 如果没有开始时间,补充开始时间
		if(StringUtils.isEmpty(reportInventoryAnalyzeEntity.getDateStart())){
			if (!CollectionUtils.isEmpty(list)) {
				Date miniDate = null;
				for (int i=0; i<list.size();i++) {
					Date temp_date = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, list.get(i).getUpdateDay());
					if(i==0){
						miniDate = temp_date;
					}else{
						Long time = miniDate.getTime();
						Long temp_time =temp_date.getTime();
						if(temp_time < time) miniDate = temp_date;
					}
					
				}
				reportInventoryAnalyzeEntity.setDateStart(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, miniDate));
			}else{
				reportInventoryAnalyzeEntity.setDateStart(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, new Date()));
			}
		}
		// 如果开始时间大于截止时间,不做处理
		Date startDate = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, reportInventoryAnalyzeEntity.getDateStart());
		Date endDate = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, reportInventoryAnalyzeEntity.getDateEnd());
		if(startDate.getTime()<=endDate.getTime()){
			List<String> days = getBetweenDay(
					reportInventoryAnalyzeEntity.getDateStart(),
					reportInventoryAnalyzeEntity.getDateEnd(),
					reportInventoryAnalyzeEntity.getGroupField());

			for (int n=0; n<days.size();n++) {
				String d = days.get(n);
				boolean has = false;
				has = queryDBSum(list, reportInventoryAnalyzeEntity, shop_sum,
						eq_sum, timeitem, d, has);
				if (!has) {
					timeitem.add(d);
					shop_sum.add("0");
					eq_sum.add("0");
				}
			}
		}
		
		result.put("shopSum", shop_sum);
		result.put("eqSum", eq_sum);
		result.put("time", timeitem);
	}
	private boolean queryDBSum(List<ReportInventoryAnalyzeEntity> list,
			ReportInventoryAnalyzeEntity reportInventoryAnalyzeEntity,
			List<String> shop_sum, List<String> eq_sum, List<String> timeitem,
			String d, boolean has) {
		if (!CollectionUtils.isEmpty(list)) {
			for (ReportInventoryAnalyzeEntity entity : list) {
				if ("UPDATE_DAY"
						.equals(reportInventoryAnalyzeEntity
								.getGroupField())
						&& d.equals(entity.getUpdateDay())) {
					timeitem.add(entity.getUpdateDay());
					shop_sum.add(entity.getShopSum());
					eq_sum.add(entity.getEqSum());
					has = true;
				} else if ("UPDATE_WEEK"
						.equals(reportInventoryAnalyzeEntity
								.getGroupField())
						&& d.equals(entity.getUpdateWeek())) {
					timeitem.add(entity.getUpdateWeek());
					shop_sum.add(entity.getShopSum());
					eq_sum.add(entity.getEqSum());
					has = true;
				} else if ("UPDATE_MONTH"
						.equals(reportInventoryAnalyzeEntity
								.getGroupField())
						&& d.equals(entity.getUpdateMonth())) {
					timeitem.add(entity.getUpdateMonth());
					shop_sum.add(entity.getShopSum());
					eq_sum.add(entity.getEqSum());
					has = true;
				}
			}
		}
		return has;
	}
	
	private void queryDbSum2(List<ReportInventoryAnalyzeEntity> list,
			ReportInventoryAnalyzeEntity reportInventoryAnalyzeEntity,
			List<String> shop_sum, List<String> eq_sum, List<String> timeitem){
		if (!CollectionUtils.isEmpty(list)) {
			for (ReportInventoryAnalyzeEntity entity : list) {
				if ("UPDATE_DAY"
						.equals(reportInventoryAnalyzeEntity
								.getGroupField())
						) {
					timeitem.add(entity.getUpdateDay());
					shop_sum.add(entity.getShopSum());
					eq_sum.add(entity.getEqSum());
				} else if ("UPDATE_WEEK"
						.equals(reportInventoryAnalyzeEntity
								.getGroupField())
						) {
					timeitem.add(entity.getUpdateWeek());
					shop_sum.add(entity.getShopSum());
					eq_sum.add(entity.getEqSum());
				} else if ("UPDATE_MONTH"
						.equals(reportInventoryAnalyzeEntity
								.getGroupField())
						) {
					timeitem.add(entity.getUpdateMonth());
					shop_sum.add(entity.getShopSum());
					eq_sum.add(entity.getEqSum());
				}
			}
		}
	}
	
	private static List<String>  getBetweenDay(String dateStart, String dateEnd,String type){
		Date daStart = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, dateStart);
		
		List<String> days = DateUtils.getAllDateBetween2Date(dateStart, dateEnd);
		List<String> list = new ArrayList<String>();
		if("UPDATE_DAY".equals(type)){
			list.addAll(days);
		}else if("UPDATE_WEEK".equals(type)){
			String lastWeekEnd = DateUtils.getWeekEndDate(dateEnd, DateUtils.TIMEPATTERN_YYYYMMDD);
			for(int i=0; ;i+=7){
				Date d = DateUtils.getDatePlusDay(daStart, i);
				String dStr = DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, d);
				String day = DateUtils.getWeekEndDate(dStr, DateUtils.TIMEPATTERN_YYYYMMDD);
				list.add(day);
				if(lastWeekEnd.equals(day)){
					break;
				}
			}
		}else if("UPDATE_MONTH".equals(type)){
			Date start = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMM, dateStart);
			Date end = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMM, dateEnd);
			Date temp = start;
			Long times = end.getTime();
			while(temp.getTime()<=times){
				list.add(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMM, temp));
				temp = DateUtils.getDatePlusMonth(temp, 1);
			}
		}
		return list;
	}
	public static void main(String[] args){
		System.out.println(getBetweenDay("2017-09-01","2017-09-11","UPDATE_WEEK"));
		
	}
	
	
	/**
	 * 查询数据列表
	 * @author cao.weiwei
	 * @date 2017年6月28日 下午4:53:16
	 * @param reportInventoryAnalyzeEntity
	 * @return
	 */
	private List<ReportInventoryAnalyzeEntity> queryReportInventoryAnalyzeEntityList(ReportInventoryAnalyzeEntity reportInventoryAnalyzeEntity){
		//  TODO 查询店铺量 10个
		// 1.是否总公司,如果是总公司, 查询出所有组织机构的,进行合计
		// 2.是否分公司,如果是分公司,查询出所有branchOrgId为当前orgId的进行合计
		// 3.是否办事处,如果是办事处,直接查询一条记录
		
		List<ReportInventoryAnalyzeEntity> list = ReportInventoryAnalyzeQueryService.queryByGroup(reportInventoryAnalyzeEntity);
		return list;
	}
	public JobResult execute(JobData jobData) throws Exception {
		JobResult jobResult = JobResult.succcessResult();
		ResponseEntity rs = scanForm(null);
		jobResult.setResultMsg(rs.getMessage());
		return jobResult;
	}
	
	/**
	 * 定时任务扫描表单计算数据
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午9:07:04
	 * @return
	 */
	public ResponseEntity scanForm(String date) {
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		try{
			List<ReportInventoryAnalyzeEntity> insertList = new ArrayList<ReportInventoryAnalyzeEntity>();
			buildInstallData(insertList,date);
			// 2.维修量
			Map<String,List<Map<String,Object>>> scrap_map =  buildRepairData(insertList,date);
			// 3.报废量
			buildScrapData(insertList,scrap_map,date);
			// 4.丢失量
			buildLoseData(insertList,date);
			setDateField(insertList,date);
			ReportInventoryAnalyzeDmlService.batchAddReportInventoryAnalyze(insertList); 
		}catch(Exception e){
			logger.debug(StringUtils.toString(e));
			rs.setMessage(StringUtils.toString(e));
			rs.setStatus(SysConstant.FAIL);
		}
		return rs;
	}
	
	/**
	 * 计算丢失量
	 * @author cao.weiwei
	 * @date 2017年7月14日 下午1:48:31
	 * @param insertList
	 */
	private void buildLoseData(List<ReportInventoryAnalyzeEntity> insertList,String date) {
		List<LoseformEntity> loseList = new ArrayList<LoseformEntity>();
		if(StringUtils.isEmpty(date)){
			  loseList =  queryYesterDayForm();
		}else{
			loseList =  queryOneDayForm(date);
		}
		 Map<String, List<LoseformEntity>> orgKeyMap = queryLoseFormListByOrg(loseList);
		 for(Map.Entry<String,List<LoseformEntity>> entry: orgKeyMap.entrySet()){
			 List<LoseformEntity> list = entry.getValue();
			 Integer sum1 = 0;	// 店铺丢失
			 Integer sum2 = 0; 	// 仓库丢失
			 Integer sum3 = 0;  // 在途丢失
			 
			 Map<String,String> shopKeyMap = new  HashMap<String,String>(); // 店铺
			 Map<String,String> storageKeyMap = new  HashMap<String,String>(); // 仓库
			 Map<String,String> ingKeyMap = new  HashMap<String,String>(); //在途
			 if(!CollectionUtils.isEmpty(list)){
				 for(LoseformEntity form: list){
					if("1".equals(form.getType())){	// 店铺丢失
						sum1+= queryEqTypeSum(form);
						shopKeyMap.put(form.getShopId(), form.getShopName());
					}else if("2".equals(form.getType())){ // 仓库丢失
						sum2+= queryEqTypeSum(form);
						storageKeyMap.put(form.getStorageId(), form.getStorageName());
					}else if("3".equals(form.getType())){ // 在途丢失
						sum3+= queryEqTypeSum(form);
					}
				 }
			 }
			OfficeEntity office = getOfficeEntity(entry.getKey()); 
			buildLoseInsertEntity(insertList, entry.getKey(), shopKeyMap, office, sum1,"31");
			buildLoseInsertEntity(insertList, entry.getKey(), storageKeyMap, office, sum2,"32");
			buildLoseInsertEntity(insertList, entry.getKey(), ingKeyMap, office, sum3,"33");
		 }
	}
	
	private void buildLoseInsertEntity(List<ReportInventoryAnalyzeEntity> insertList,
			String orgId,
			Map<String, String> shopKeyMap, 
			OfficeEntity office,
			Integer eqSum,
			String typeId) {
		ReportInventoryAnalyzeEntity org_install_shop = new ReportInventoryAnalyzeEntity();
		Integer shop_sum = shopKeyMap.size(); 
		org_install_shop.setBusinessType(typeId);// 安装量
		org_install_shop.setOrgId(orgId);
		org_install_shop.setBranchOrgId(office.getBranchOrgId());
		org_install_shop.setBranchOrgName(office.getBranchOrgName());
		org_install_shop.setOfficeOrgId(office.getOfficeOrgId());
		org_install_shop.setOfficeOrgName(office.getOfficeOrgName());
		org_install_shop.setEqSum(eqSum.toString());
		org_install_shop.setShopSum(shop_sum.toString());
		insertList.add(org_install_shop);
	}
	
	private Integer queryEqTypeSum(LoseformEntity form) {
		LoseformBarcodeEntity codeEntity = new LoseformBarcodeEntity();
		codeEntity.setWoNo(form.getWoNo());
		List<LoseformBarcodeEntity> list = loseformBarcodeQueryService.queryAllLoseformBarcode(codeEntity);
		Integer sum = 0;
		if(!CollectionUtils.isEmpty(list)){
			for(LoseformBarcodeEntity e: list){
				String eqNum = e.getEqNum();
				sum+= Integer.parseInt(eqNum);
			}
		}
		return sum;
	}
	private Map<String, List<LoseformEntity>> queryLoseFormListByOrg(
			List<LoseformEntity> loseList) {
		Map<String,List<LoseformEntity>> orgKeyMap = new HashMap<String,List<LoseformEntity>>();
		buildOrgLoseformEntity(orgKeyMap);
		if(!CollectionUtils.isEmpty(loseList)){
			for(LoseformEntity lose: loseList){
				String orgId = lose.getOrgId();
				orgKeyMap.get(orgId).add(lose);
			}
		}
		return orgKeyMap;
	}
	private List<LoseformEntity> queryYesterDayForm() {
		LoseformEntity loseform = new LoseformEntity();
		Date todayDate = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, DateUtils.getCurrentTime().substring(0, 10));
		Date yesterDate = DateUtils.getDatePlusDay(todayDate, -1);
		loseform.setPassTimeStart(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, yesterDate));
		loseform.setPassTimeEnd(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, todayDate));
		loseform.setStatus("3"); // 审批通过
		List<LoseformEntity> list = loseformQueryService.queryAllLoseform(loseform);
		return list;
	}
	private List<LoseformEntity> queryOneDayForm(String date) {
		LoseformEntity loseform = new LoseformEntity();
		Date theDate = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, date);// 当天
		Date theDateAfter = DateUtils.getDatePlusDay(theDate, 1);
		loseform.setPassTimeStart(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, theDate));
		loseform.setPassTimeEnd(DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, theDateAfter));
		loseform.setStatus("3"); // 审批通过
		List<LoseformEntity> list = loseformQueryService.queryAllLoseform(loseform);
		return list;
	}	/**
	 * 设置时间
	 * @author cao.weiwei
	 * @date 2017年7月10日 上午10:38:05
	 * @param insertList
	 */
	private void setDateField(List<ReportInventoryAnalyzeEntity> insertList,String date) {
		//  当日
		String today = DateUtils.getCurrentTime().substring(0, 10);
		Date todayD = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, today);
		Date yesterD = DateUtils.getDatePlusDay(todayD, -1);// 昨日
		String yester = DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, yesterD);
		String weekEnd = DateUtils.getWeekEndDate(yester,DateUtils.TIMEPATTERN_YYYYMMDD);
		String month = yester.substring(0, 7);
		// 某日
		String theDay = null;
		String theWeekEnd = null;
		String theMonth = null;
		if(!StringUtils.isEmpty(date)){
			Date thedayD = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, date);
			theDay = DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, thedayD);
			theWeekEnd = DateUtils.getWeekEndDate(theDay,DateUtils.TIMEPATTERN_YYYYMMDD);
			theMonth = theDay.substring(0, 7);
		}
		for(ReportInventoryAnalyzeEntity e: insertList){
			e.setUpdateDay(yester);
			e.setUpdateTime(yester);
			e.setUpdateMonth(month);
			e.setUpdateWeek(weekEnd);
			if(!StringUtils.isEmpty(date)){
				e.setUpdateTime(theDay);
				e.setUpdateDay(theDay);
				e.setUpdateMonth(theMonth);
				e.setUpdateWeek(theWeekEnd);
			}
		}
	}
	/**
	 * 计算安装单数据
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:33:08
	 * @param insertList
	 */
	private void buildInstallData(List<ReportInventoryAnalyzeEntity> insertList,String date) {
		List<UserTask> taskList = queryInstallTask(date);
		Map<String, List<Map<String, Object>>> orgKeyMap = queryInstallFormListByOrg(taskList);
		queryInstallFormDetail(insertList, orgKeyMap);
	}
	
	/**
	 * 计算报废数量
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:41:23
	 * @param insertList
	 */
	private void buildScrapData(List<ReportInventoryAnalyzeEntity> insertList ,Map<String,List<Map<String,Object>>> scrap_map,String date) {
		List<UserTask> taskList = queryScrapTask(date);
		Map<String, List<Map<String, Object>>> orgKeyMap = queryScrapFormListByOrg(taskList);
		queryScrapFormDetail(insertList, orgKeyMap ,scrap_map);
	}
	/**
	 * 计算维修单数据
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:41:23
	 * @param insertList
	 */
	private Map<String,List<Map<String,Object>>>  buildRepairData(List<ReportInventoryAnalyzeEntity> insertList,String date) {
		List<UserTask> taskList = queryRepairTask(date);
		Map<String, List<Map<String, Object>>> orgKeyMap = queryRepairFormListByOrg(taskList);
		Map<String,List<Map<String,Object>>> scrapOrgMap = new HashMap<String,List<Map<String,Object>>>();
		buildOrgMap(scrapOrgMap);
		queryRepairFormDetail(insertList, orgKeyMap,scrapOrgMap);
		return scrapOrgMap;
	}
	/**
	 * 查询安装单的数量信息
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:36:33
	 * @param insertList
	 * @param orgKeyMap
	 */
	private void queryInstallFormDetail(List<ReportInventoryAnalyzeEntity> insertList,
			Map<String, List<Map<String, Object>>> orgKeyMap) {
		for(Map.Entry<String,List<Map<String,Object>>> entry: orgKeyMap.entrySet()){
			// 每个组织机构插入数条数据
			String orgId = entry.getKey();
			List<Map<String,Object>> installlist = entry.getValue();
			Integer equipment_sum = 0;
			Map<String,String> shopKeyMap = new HashMap<String,String>();
			for(Map<String,Object> maintable: installlist){
				shopKeyMap.put(maintable.get("SHOP_ID").toString(), maintable.get("SHOP_NAME").toString());
				List<Map<String,Object>> installTableList = dymcformQueryService.queryList(buildQuerySubTableSql(maintable.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_INSTALL_DETAIL));
				for(Map<String,Object> item: installTableList){
					equipment_sum += Integer.parseInt(item.get("EQ_NUM").toString());
				}
			}
			ReportInventoryAnalyzeEntity org_install_shop = new ReportInventoryAnalyzeEntity();
			OfficeEntity office = getOfficeEntity(orgId); 
			Integer shop_sum = shopKeyMap.size(); 
			org_install_shop.setBusinessType("1");// 安装量
			org_install_shop.setOrgId(orgId);
			org_install_shop.setBranchOrgId(office.getBranchOrgId());
			org_install_shop.setBranchOrgName(office.getBranchOrgName());
			org_install_shop.setOfficeOrgId(office.getOfficeOrgId());
			org_install_shop.setOfficeOrgName(office.getOfficeOrgName());
			org_install_shop.setEqSum(equipment_sum.toString());
			org_install_shop.setShopSum(shop_sum.toString());
			insertList.add(org_install_shop);
		}
	}
	
	/**
	 * 计算维修单数量
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:47:11
	 * @param insertList
	 * @param orgKeyMap
	 */
	private void queryRepairFormDetail(List<ReportInventoryAnalyzeEntity> insertList,
			Map<String, List<Map<String, Object>>> orgKeyMap,
			Map<String,List<Map<String,Object>>> scrapOrgMap ) {
		for(Map.Entry<String,List<Map<String,Object>>> entry: orgKeyMap.entrySet()){
			// 每个组织机构插入数条数据
			String orgId = entry.getKey();
			List<Map<String,Object>> installlist = entry.getValue();
			Integer equipment_sum = 0;
			Map<String,String> shopKeyMap = new HashMap<String,String>();
			for(Map<String,Object> maintable: installlist){
				scrapOrgMap.get(orgId).add(maintable);// 维修的数据,在计算报废量的时候需要再计算一遍
				List<Map<String,Object>> serviceTableList = dymcformQueryService.queryList(buildQuerySubTableSql(maintable.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_EQUIPMENT_SERVICE_SERVICE));
				if(!CollectionUtils.isEmpty(serviceTableList)){
					shopKeyMap.put(maintable.get("SHOP_ID").toString(), maintable.get("SHOP_NAME").toString());
					for(Map<String,Object> item: serviceTableList){
						equipment_sum += Integer.parseInt(item.get("EQ_NUM").toString());
					}
				}
			}
			ReportInventoryAnalyzeEntity org_repair_shop = new ReportInventoryAnalyzeEntity();
			OfficeEntity office = getOfficeEntity(orgId); 
			Integer shop_sum = shopKeyMap.size(); 
			org_repair_shop.setBusinessType("2");// 维修量
			org_repair_shop.setOrgId(orgId);
			org_repair_shop.setBranchOrgId(office.getBranchOrgId());
			org_repair_shop.setBranchOrgName(office.getBranchOrgName());
			org_repair_shop.setOfficeOrgId(office.getOfficeOrgId());
			org_repair_shop.setOfficeOrgName(office.getOfficeOrgName());
			org_repair_shop.setEqSum(equipment_sum.toString());
			org_repair_shop.setShopSum(shop_sum.toString());
			org_repair_shop.setUpdateDay(DateUtils.getCurrentTime().substring(0, 10));
			org_repair_shop.setUpdateMonth(DateUtils.getCurrentTime().substring(0, 6));
			org_repair_shop.setUpdateWeek(DateUtils.getWeekEndDate(DateUtils.getCurrentTime().substring(0, 10),DateUtils.TIMEPATTERN_YYYYMMDD));
			insertList.add(org_repair_shop);
			
		}
	}
	/**
	 * 计算报废数据
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:48:52
	 * @param insertList
	 * @param orgKeyMap
	 */
	private void queryScrapFormDetail(List<ReportInventoryAnalyzeEntity> insertList,
			Map<String, List<Map<String, Object>>> orgKeyMap ,Map<String, List<Map<String, Object>>> scrap_map) {
		for(Map.Entry<String,List<Map<String,Object>>> entry: orgKeyMap.entrySet()){
			// 每个组织机构插入数条数据
			String orgId = entry.getKey();
			List<Map<String,Object>> installlist = entry.getValue();
			Integer equipment_sum = 0;
			Map<String,String> shopKeyMap = new HashMap<String,String>();
			for(Map<String,Object> maintable: installlist){
				shopKeyMap.put(maintable.get("STORAGE_ID").toString(), maintable.get("STORAGE_NAME").toString());
				List<Map<String,Object>> callTableList = dymcformQueryService.queryList(buildQuerySubTableSql(maintable.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_EQUIPMENT_SCRAP_LIST));
				for(Map<String,Object> item: callTableList){
					equipment_sum += Integer.parseInt(item.get("EQ_NUM").toString());
				}
			}
			ReportInventoryAnalyzeEntity org_scrap_shop = new ReportInventoryAnalyzeEntity();
			ReportInventoryAnalyzeEntity org_scrap_equipment = new ReportInventoryAnalyzeEntity();
			OfficeEntity office = getOfficeEntity(orgId); 
			
			org_scrap_shop.setBusinessType("4");// 报废量
			org_scrap_shop.setOrgId(orgId);
			org_scrap_shop.setBranchOrgId(office.getBranchOrgId());
			org_scrap_shop.setBranchOrgName(office.getBranchOrgName());
			org_scrap_shop.setOfficeOrgId(office.getOfficeOrgId());
			org_scrap_shop.setOfficeOrgName(office.getOfficeOrgName());
			// 合计维修单中的报废设备店铺和数量
			if(scrap_map.containsKey(orgId) && scrap_map.get(orgId).size()>0){
				for(Map<String,Object> mainObj: scrap_map.get(orgId)){
					List<Map<String,Object>> callTableList = dymcformQueryService.queryList(buildQuerySubTableSql(mainObj.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_EQUIPMENT_SERVICE_CALL));
					if(!CollectionUtils.isEmpty(callTableList)){
						shopKeyMap.put(mainObj.get("SHOP_ID").toString(), mainObj.get("SHOP_NAME").toString());
						for(Map<String,Object> item: callTableList){
							equipment_sum += Integer.parseInt(item.get("EQ_NUM").toString());
						}
					}
				}
			}
			Integer shop_sum = shopKeyMap.size(); 
			org_scrap_shop.setShopSum(shop_sum.toString());
			org_scrap_shop.setEqSum(equipment_sum.toString());
			insertList.add(org_scrap_shop);
		}
	}
	/**
	 * 查询每个组织机构的报废单
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:35:09
	 * @param taskList
	 * @return
	 */
	private Map<String, List<Map<String, Object>>> queryScrapFormListByOrg(
			List<UserTask> taskList) {
		Map<String,List<Map<String,Object>>> orgKeyMap = new HashMap<String,List<Map<String,Object>>>();
		buildOrgMap(orgKeyMap);
		for(UserTask task: taskList){
			List<Map<String,Object>> mainTableList = dymcformQueryService.queryList(buildQueryScrapTableSql(task.getBusinessNo()));
			if(!CollectionUtils.isEmpty(mainTableList)){
				String orgId = mainTableList.get(0).get("ORG_ID").toString();
				if(orgKeyMap.containsKey(orgId)){
					orgKeyMap.get(orgId).add(mainTableList.get(0));
				}
			}
		}
		return orgKeyMap;
	}
	/**
	 * 查询每个组织机构的维修单
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:55:10
	 * @param taskList
	 * @return
	 */
	private Map<String, List<Map<String, Object>>> queryRepairFormListByOrg(
			List<UserTask> taskList) {
		Map<String,List<Map<String,Object>>> orgKeyMap = new HashMap<String,List<Map<String,Object>>>();
		buildOrgMap(orgKeyMap);
		for(UserTask task: taskList){
			List<Map<String,Object>> mainTableList = dymcformQueryService.queryList(buildQueryRepairTableSql(task.getBusinessNo()));
			if(!CollectionUtils.isEmpty(mainTableList)){
				String orgId = mainTableList.get(0).get("ORG_ID").toString();
				if(orgKeyMap.containsKey(orgId)){
					orgKeyMap.get(orgId).add(mainTableList.get(0));
				}
			}
		}
		return orgKeyMap;
	}
	/**
	 * 查询每个组织机构的安装单
	 * @author cao.weiwei
	 * @date 2017年7月4日 上午11:54:43
	 * @param taskList
	 * @return
	 */
	private Map<String, List<Map<String, Object>>> queryInstallFormListByOrg(
			List<UserTask> taskList) {
		Map<String,List<Map<String,Object>>> orgKeyMap = new HashMap<String,List<Map<String,Object>>>();
		buildOrgMap(orgKeyMap);
		for(UserTask task: taskList){
			List<Map<String,Object>> mainTableList = dymcformQueryService.queryList(buildQueryInstallTableSql(task.getBusinessNo()));
			if(!CollectionUtils.isEmpty(mainTableList)){
				String orgId = mainTableList.get(0).get("ORG_ID").toString();
				if(orgKeyMap.containsKey(orgId)){
					orgKeyMap.get(orgId).add(mainTableList.get(0));
				}
			}
		}
		return orgKeyMap;
	}
	private List<UserTask> queryInstallTask(String date) {
		UserTask userTask = new UserTask();
		userTask.setWorkflowId(ReportConstant.WORKFLOWID_INSTALL);
		List<UserTask> taskList = null;
		if(StringUtils.isEmpty(date)){
			taskList = activitiTaskQueryService.queryFinishTaskListByProcess(userTask);
		}else{
			taskList = activitiTaskQueryService.queryFinishTaskListByProcessDay(userTask,date);
		}
		return taskList;
	}
	private List<UserTask> queryRepairTask(String date) {
		UserTask userTask = new UserTask();
		userTask.setWorkflowId(ReportConstant.WORKFLOWID_EQUIPMENT_SERVICE);
		List<UserTask> taskList = new ArrayList<UserTask>();
		if(StringUtils.isEmpty(date)){
			taskList = activitiTaskQueryService.queryFinishTaskListByProcess(userTask);
		}else{
			taskList =  activitiTaskQueryService.queryFinishTaskListByProcessDay(userTask,date);
		}
		return taskList;
	}
	private List<UserTask> queryScrapTask(String date) {
		UserTask userTask = new UserTask();
		userTask.setWorkflowId(ReportConstant.WORKFLOWID_EQUIPMENT_SCRAP);
		List<UserTask> taskList = new ArrayList<UserTask>();
		if(StringUtils.isEmpty(date)){
			taskList = activitiTaskQueryService.queryFinishTaskListByProcess(userTask);
		}else{
			taskList =  activitiTaskQueryService.queryFinishTaskListByProcessDay(userTask,date);
		}
		return taskList;
	}
	
	private void buildOrgMap(Map<String,List<Map<String,Object>>> orgMap){
		List<OrgEntity> orgList = orgQueryService.queryAllOrg(new OrgEntity());
		for(OrgEntity orgEntity: orgList){
			orgMap.put(orgEntity.getOrgId(), new ArrayList<Map<String,Object>>());
		}
	}
	private void buildOrgLoseformEntity(Map<String,List<LoseformEntity>> orgMap){
		List<OrgEntity> orgList = orgQueryService.queryAllOrg(new OrgEntity());
		for(OrgEntity orgEntity: orgList){
			orgMap.put(orgEntity.getOrgId(), new ArrayList<LoseformEntity>());
		}
	}
	private String buildQueryInstallTableSql(String wo_no){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ID,WO_NO,SHOP_ID,SHOP_NAME,ORG_ID,CREATE_USER,CREATER,CREATE_TIME ");
		sb.append("FROM ").append(ReportConstant.DYMCFORM_TABLE_INSTALL).append(" where ");
		sb.append("WO_NO ='").append(wo_no).append("' and INSTALL_RESULT='1' and CHECK_RESULT='1' ");
		sb.append(";");
		return sb.toString();
	}
	
	private String buildQuerySubTableSql(String mainTableId,String subTableName){
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT EQ_TYPE_ID,EQ_TYPE_NAME,EQ_NUM ");
		sb.append(" FROM ").append(subTableName);
		sb.append(" WHERE ");
		sb.append(" MAIN_TABLE_ID ='").append(mainTableId).append("'");
		sb.append(" AND IS_DEL = '0';");
		return sb.toString();
	}
	
	private OfficeEntity getOfficeEntity(String orgId){
		OfficeEntity ofe = new OfficeEntity();
		OrgEntity orgEntity = new OrgEntity();
		List<OrgEntity> orgList = orgQueryService.queryAllOrg(orgEntity);
		for(OrgEntity o: orgList){
			if(o.getOrgId().equals(orgId)){
				if(o.getOrgType().equals("0")){
					ofe.setBranchOrgId(o.getOrgId());
					ofe.setBranchOrgName(o.getOrgName());
					ofe.setOfficeOrgId(o.getOrgId());
					ofe.setOfficeOrgName(o.getOrgName());
				}else if(o.getOrgType().equals("1")){
					ofe.setBranchOrgId(o.getOrgId());
					ofe.setBranchOrgName(o.getOrgName());
					ofe.setOfficeOrgId(o.getOrgId());
					ofe.setOfficeOrgName(o.getOrgName());
				}else if(o.getOrgType().equals("2")){
					ofe.setBranchOrgId(o.getParentOrgId());
					ofe.setBranchOrgName(o.getParentOrgName());
					ofe.setOfficeOrgId(o.getOrgId());
					ofe.setOfficeOrgName(o.getOrgName());
				}
			}
		}
		return ofe;
	}
	
	
	
	private String buildQueryRepairTableSql(String wo_no){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ID,WO_NO,SHOP_ID,SHOP_NAME,ORG_ID,CREATE_USER,CREATER,CREATE_TIME ");
		sb.append("FROM ").append(ReportConstant.DYMCFORM_TABLE_EQUIPMENT_SERVICE).append(" where ");
		sb.append("WO_NO ='").append(wo_no).append("' and CHECK_RESULT='1' and CONFIRM_RESULT='1' ");
		sb.append(";");
		return sb.toString();
	}
	private String buildQueryScrapTableSql(String wo_no){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ID,WO_NO,STORAGE_ID,STORAGE_NAME,STORAGE_ADDR,STORAGE_ADDR_ID,ORG_ID,CREATE_USER,CREATE_TIME ");
		sb.append("FROM ").append(ReportConstant.DYMCFORM_TABLE_EQUIPMENT_SCRAP).append(" where ");
		sb.append("WO_NO ='").append(wo_no).append("' and CHECK_RESULT='1' ");
		sb.append(";");
		return sb.toString();
	}
	public ResponseEntity testTask(String date ) {
		if(StringUtils.isEmpty(date)){
			return scanForm(null);
		}else{
			return scanForm(date);
		}
	}
}
	

